package org.nod.atgm.model;

import java.io.IOException;
import java.util.HashMap;

import org.nod.atgm.gameobjects.APC;
import org.nod.atgm.gameobjects.ArtilleryShell;

import android.app.Activity;

import com.threed.jpct.Config;
import com.threed.jpct.Loader;
import com.threed.jpct.Matrix;
import com.threed.jpct.Object3D;
import com.threed.jpct.Primitives;
import com.threed.jpct.SimpleVector;
import com.threed.jpct.Texture;
import com.threed.jpct.TextureManager;

public class PrecompiledObjectManager {
	
	private static PrecompiledObjectManager instance = null;
	
	private PrecompiledObjectManager() {
		// TODO Auto-generated constructor stub
	}
	
	HashMap <String, Object3D> precompiledObjects;
	
	public static PrecompiledObjectManager getInstance() {
		if (instance == null)
			instance = new PrecompiledObjectManager();
		return instance;
	}
	
	public static void initPrecompiledObjects(Activity context) {
		getInstance();
		if (instance.precompiledObjects == null) {
			instance.precompiledObjects = new HashMap<String, Object3D>();
			instance.put(ArtilleryShell.ID, ArtilleryShell.createBasicArtilleryShellObject());
			Config.useRotationPivotFrom3DS = true;
			try {
				Texture texture = new Texture(context.getAssets().open("apc.png"));
				TextureManager.getInstance().addTexture("apc", texture);
				
				instance.put(APC.ID, loadModel(context,"apc.3ds",1f));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

	public void put(String id, Object3D object) {
		precompiledObjects.put(id,object);
	}

	public Object3D getPrecompiledObject(String id) {
		return precompiledObjects.get(id);
	}
	
	protected static Object3D loadModel(Activity context, String filename, float scale) throws IOException {
		Object3D model = Loader.load3DS(context.getAssets().open(filename), scale)[0];
//            temp.rotateX((float)( -.5*Math.PI));
//        model.rotateMesh();
//        model.setRotationMatrix(new Matrix());
//        model.rotateX((float) (-Math.PI / 2f));
        model.rotateX((float)( -0.5*Math.PI));
        model.setTexture("apc");
        model.build();
        model.setCenter(SimpleVector.ORIGIN);
        model.setOrigin(SimpleVector.ORIGIN);
        model.scale(0.2f);
        model.compile();
        return model;
//        Object3D[] model = Loader.load3DS(context.getAssets().open(filename), scale);
//        Object3D o3d = new Object3D(0);
//        Object3D temp = null;
//        for (int i = 0; i < model.length; i++) {
//            temp = model[i];
//            temp.setCenter(SimpleVector.ORIGIN);
//            temp.rotateMesh();
//            temp.setRotationMatrix(new Matrix());
//            o3d = Object3D.mergeObjects(o3d, temp);
//            o3d.build();
//        }
//        o3d.compile();
//        return o3d;
    }
}
